import * as buycarService from '../services/buycar';

import { Toast } from 'antd-mobile'
import { Link, browserHistory } from 'dva/router';
import { getUserId } from '../utils/utils'

export default {

  namespace: 'buycar',

  state: {
      cartList: []
  },

  subscriptions: {
    setup({ dispatch, history }) {  // eslint-disable-line
    }
  },

  effects: {
    *modifyCartNumber({ payload }, { call, put }) {
      const { data } = yield call(buycarService.modifyCartNumber, payload)

      if(!(data && data.status === 1)){
        // success
        Toast.info('修改商品数量失败', 1);
      } 
    },
    *fetchCartList({ payload }, { call, put }) {
      const { data } = yield call(buycarService.fetchCartList, payload)
      
      yield put({
        type: 'saveCartList',
        payload: {
          cartList: data && data.result || []
        }
      })
    },
    *deleteCart({ payload }, { call, put }) {
      const { data } = yield call(buycarService.deleteCart, payload) 
      if(data && data.status === 1) {
        // success
        Toast.info('删除成功', 1);
        // reload
        yield put({ 
            type: 'fetchCartList', 
            payload: +getUserId() 
        });
      } else {
        // error
        Toast.info(`${data && data.msg || '删除失败，请稍后再试'}`);
      }
    },
    *reload(action, { put, select }) {
      yield put({ type: 'fetchAddress', payload: +getUserId()})
    }
  },

  reducers: {
    saveCartList(state, { payload: { cartList }}) {
      return { ...state, cartList }
    }
  }

};
